package com.example.content;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class MyProvider extends ContentProvider {
    private Context mContext;  // 上下文
    DBHelper mDbHelper = null;  // 数据库帮助类
    SQLiteDatabase db = null;

    public static final String AUTOHORITY = "com.example.content.myprovider";  // 权限标识
    public static final int User_Code = 1;  // 用户表操作码
    public static final int Job_Code = 2;   // 工作表操作码

    private static final UriMatcher mMatcher;  // Uri匹配器
    static {
        mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        mMatcher.addURI(AUTOHORITY, "user", User_Code);
        mMatcher.addURI(AUTOHORITY, "job", Job_Code);
    }
    @Override
    public boolean onCreate() {
        //数据库初始化。
        mContext = getContext();
        mDbHelper = new DBHelper(getContext());  // 初始化数据库帮助类
        db = mDbHelper.getWritableDatabase();  // 获取可写数据库实例
        db.execSQL("delete from user");  // 清空用户表数据
        db.execSQL("insert into user values(1,'Carson');");  // 插入用户数据
        db.execSQL("insert into user values(2,'Kobe');");
        db.execSQL("delete from job");  // 清空工作表数据
        db.execSQL("insert into job values(1,'Android');");  // 插入工作数据
        db.execSQL("insert into job values(2,'iOS');");
        return true;
    }
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        String table = getTableName(uri);  // 获取操作的表名
        db.insert(table, null, values);  // 执行插入操作
        mContext.getContentResolver().notifyChange(uri, null);  // 通知数据变化
        return uri;
    }
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        String table = getTableName(uri);  // 获取操作的表名
        return db.query(table, projection, selection, selectionArgs, null, null, sortOrder, null);  // 执行查询操作
    }
    @Override
    public int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {
        // 这里可以添加更新操作的具体实现
        return 0;
    }
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // 这里可以添加删除操作的具体实现
        return 0;
    }
    @Override
    public String getType(Uri uri) {
        return null;
    }
    // 根据Uri匹配返回对应的表名
    private String getTableName(Uri uri) {
        String tableName = null;
        switch (mMatcher.match(uri)) {
            case User_Code:
                tableName = DBHelper.USER_TABLE_NAME;
                break;
            case Job_Code:
                tableName = DBHelper.JOB_TABLE_NAME;
                break;
        }
        return tableName;
    }
}